require 'zdc.doc'
require 'zsvc.que'
require 'zsvc.packet'
require 'zsvc.accept'
require 'zsvc.evhandle'
local monutil=require 'zsvc.monutil'

module(..., package.seeall)

local Notifyhandle= {}
zsvc.evhandle.InitEvent(Notifyhandle)
local Notifyhandle_mt = {__metatable = {}, __index = Notifyhandle}


function new(params)
	local obj = setmetatable({name=params.name,mon=params.mon,fd=params.fd,react=params.react,clis=params.clis,logger=params.logger,que=zsvc.que.new(),sp=zsvc.packet.new(),rp=zsvc.packet.new()}, Notifyhandle_mt)
	monutil.mon_start(obj)
	obj:_bv_init()
	return obj
end

function Notifyhandle:OnClose()
	if self.fd then
		self:_bv_close()
		monutil.mon_end(self)
		self.fd:close()
		self.fd=nil
	end
end

function Notifyhandle:SendPacket(np)
	self:OnClose()
	error'Notifyhandle should not send packet'
end

function Notifyhandle:OnMsg(packet)
	local h=packet:ParseHeader()
	local pos,ch=packet:GetCH()
	local cli=ch.to
	local clip=ch.path and ch.path[#ch.path]
	if type(cli)=='string' then
		local clifd=self.clis:Find(cli,clip)
		if clifd then
			local np=zsvc.packet.new()
			--if ch.path then table.remove(ch.path) end
			np:SetMsg2(h.appid,ch,packet.buf,pos)
			clifd:SendPacket(np)
			return
		end
		self.logger:error("Notifyhandle can't find client " .. cli)
		return
	elseif type(cli)=='table' then
		for i=1,#cli do
			local cliobj=cli[i]
			if type(cliobj)=='string' then
				local clifd=self.clis:Find(cliobj,clip)
				if clifd then
					local np=zsvc.packet.new()
					ch.to=cliobj
					--if ch.path then table.remove(ch.path) end
					np:SetMsg2(h.appid,ch,packet.buf,pos)
					clifd:SendPacket(np)
					return
				end
				self.logger:info("Notifyhandle[table] can't find client " .. tostring(cliobj))
			else
				self.logger:error("Notifyhandle to=[table] han unknow obj " ..  tostring(cliobj))
			end
		end
		return
	end
	self.logger:error("Notifyhandle recv a bad msg from app, no path")
	return
end
